package com.jxltech.unicam;

import cn.hutool.core.collection.CollectionUtil;
import com.github.sarxos.webcam.Webcam;
import com.jxltech.unicam.utils.Constants;
import com.jxltech.unicam.utils.DerbyDb;
import com.jxltech.unicam.utils.SerialPortManager;

import java.awt.*;
import java.util.ArrayList;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

/**
 * Dialog where you configure the settings
 *
 * @author Jelmerro
 */
public class SettingsDialog extends JDialog {

	private final DefaultComboBoxModel webcamModel;
	private final JComboBox webcamBox;
	private final JTextField XField;
	private final JTextField YField;
	private final JTextField GField;
	private final JComboBox portComboBox = new JComboBox();
	private JLabel ggLabel = new JLabel("光感值:0");
	Object[] options = {"确定", "取消"};

	/**
	 * Creates the SettingsDialog
	 */
	public SettingsDialog() {
		//Call super method
		super(Frame.getInstance(), "个性化（请谨慎设置）", ModalityType.APPLICATION_MODAL);
		//Set properties
		setResizable(false);
		getRootPane().setBorder(new EmptyBorder(20, 20, 20, 20));
		setBounds(40, 40, 40, 40);
		setLayout(new GridLayout(0, 2, 10, 10));
		setSize(new Dimension(500, 220));
		setPreferredSize(new Dimension(500, 220));
		Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation(screen.width / 2 + 175, screen.height / 2 + 125);

		//设置端口选项
		ArrayList<String> mCommList = SerialPortManager.findPorts();
		mCommList.forEach(item-> portComboBox.addItem(item));

		//分辨率
		XField = new JTextField("" + 0);
		YField = new JTextField("" + 0);
		//光感阈值
		GField = new JTextField("" + 0);

		webcamModel = new DefaultComboBoxModel();
		webcamBox = new JComboBox(webcamModel);
		webcamBox.setMaximumRowCount(10);
		if (!Constants.config.inited()) {
			webcamBox.addActionListener(e -> {
				//设置默认分辨率
				Dimension d = getResolution();
				if (d != null) {
					XField.setText("" + d.width);
					YField.setText("" + d.height);
				} else {
					XField.setText("" + 0);
					YField.setText("" + 0);
				}
			});
			//设置默认光感阈值
			GField.setText("" + Constants.defaultGLimit);
			//设置默认端口号，选择最后一个
			if(CollectionUtil.isNotEmpty(mCommList)) portComboBox.setSelectedItem(mCommList.get(mCommList.size() - 1));
			updateConfig();
		} else {
			webcamBox.addActionListener(e -> {
				XField.setText("" + Constants.config.getxVal());
				YField.setText("" + Constants.config.getyVal());
			});
			GField.setText("" + Constants.config.getgVal());
			portComboBox.setSelectedItem(Constants.config.getpVal());
		}

		JButton doubleButton = new JButton("2X");
		//Doubles the input fields
		doubleButton.addActionListener(e -> {
			try {
				XField.setText("" + (Integer.parseInt(XField.getText()) * 2));
				YField.setText("" + (Integer.parseInt(YField.getText()) * 2));
			} catch (Exception ex) {

			}
		});
		JButton halfButton = new JButton("/2");
		//Halves the input fields
		halfButton.addActionListener(e -> {
			try {
				XField.setText("" + (Integer.parseInt(XField.getText()) / 2));
				YField.setText("" + (Integer.parseInt(YField.getText()) / 2));
			} catch (Exception ex) {

			}
		});
		JButton applyButton = new JButton("应用");
		//Applies the resolution for the selected webcam
		//This will start the same process as detecting the resolution
		applyButton.addActionListener(e -> {
			//If the input fields contain no only numbers, show a warning and reshow the dialog
			try {
				int selectedValue = JOptionPane.showOptionDialog(Frame.getInstance(),
						"确定更新配置么？", "配置修改",
						JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
				if (selectedValue == 0) {
					setVisible(false);
					//设置光感阀值
					GField.setText("" + GField.getText());

					//设置分辨率
					Dimension dimension = new Dimension(Integer.parseInt(XField.getText()), Integer.parseInt(YField.getText()));
					LoadingDialog loadingDialog = new LoadingDialog();
					loadingDialog.load(getLeftWebcam(), getRightWebcam(), dimension);
					updateConfig();
					//重启端口
					SerialPortManager.resetSerialPort();

				}
			} catch (NumberFormatException ex) {
				JOptionPane.showMessageDialog(null, "只能输入数字", "警告", JOptionPane.WARNING_MESSAGE);
				setVisible(true);
			}
		});

		JButton revertButton = new JButton("恢复默认");
		revertButton.addActionListener(e -> {
			//恢复默认值
			try {
				int selectedValue = JOptionPane.showOptionDialog(Frame.getInstance(),
						"确定恢复默认值么？", "恢复默认",
						JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
				if (selectedValue == 0) {
					setVisible(false);
					GField.setText("" + Constants.defaultGLimit);
					Dimension d = getResolution();
					if (d != null) {
						XField.setText("" + d.width);
						YField.setText("" + d.height);
					} else {
						XField.setText("" + 0);
						YField.setText("" + 0);
					}
					Dimension dimension = new Dimension(Integer.parseInt(XField.getText()), Integer.parseInt(YField.getText()));
					LoadingDialog loadingDialog = new LoadingDialog();
					loadingDialog.load(getLeftWebcam(), getRightWebcam(), dimension);
					updateConfig();
					//重启端口
					SerialPortManager.resetSerialPort();

				}
			} catch (NumberFormatException ex) {
				JOptionPane.showMessageDialog(null, "只能输入数字", "警告", JOptionPane.WARNING_MESSAGE);
				setVisible(true);
			}
		});

		JButton cancelButton = new JButton("取消");
		//Hides the dialog
		cancelButton.addActionListener(e -> {
			setVisible(false);
		});
		//Add items
//		add(new JLabel("摄像头:"));
//		add(webcamBox);
		add(new JLabel("分辨率:"));
		Box box = new Box(BoxLayout.X_AXIS);
		box.add(doubleButton);
		box.add(XField);
		box.add(YField);
		box.add(halfButton);
		add(box);

		add(new JLabel("光感阈值:"));
		Box gBox = new Box(BoxLayout.X_AXIS);
		gBox.add(GField);
		gBox.add(ggLabel);
		add(gBox);

		add(new JLabel("端口:"));
		Box pBox = new Box(BoxLayout.X_AXIS);
		pBox.add(portComboBox);
		add(pBox);

		add(applyButton);
//		add(cancelButton);
		add(revertButton);
	}

	private void updateConfig() {
		Constants.config.setxVal(Integer.parseInt(XField.getText()));
		Constants.config.setyVal(Integer.parseInt(YField.getText()));
		Constants.config.setgVal(Integer.parseInt(GField.getText()));
		Constants.config.setpVal(String.valueOf(portComboBox.getSelectedItem()));
		DerbyDb.updateConifg(Constants.config);
	}

	/**
	 * Refreshes the list of webcams
	 */
	public void refreshWebcams() {
		webcamModel.removeAllElements();
		for (Webcam webcam : Webcam.getWebcams()) {
			webcamModel.addElement(webcam);
		}
	}

	/**
	 * Returns the Webcam that is Left
	 *
	 * @return webcam Webcam
	 */
	public Webcam getLeftWebcam() {
		return (Webcam) webcamBox.getItemAt(0);
	}

	/**
	 * Returns the Webcam that is right
	 *
	 * @return webcam Webcam
	 */
	public Webcam getRightWebcam() {
		if (webcamBox.getItemCount() > 1)
			return (Webcam) webcamBox.getItemAt(1);
		else
			return (Webcam) webcamBox.getItemAt(0);
	}

	/**
	 * Returns the current resolution, it returns 640x480 when there is no panel
	 *
	 * @return resolution Dimension
	 */
	private Dimension getResolution() {
		if (Frame.getInstance().getLeftPanel() != null) {
			return Frame.getInstance().getLeftPanel().getPreferredSize();
		}
		return new Dimension(640, 480);
	}

	public void setGgLabelValue(int light){
		ggLabel.setText("光感值:" + light);
	}
}
